#include "../source/server.hpp"

EventLoop base_loop;
std::unordered_map<uint64_t, PtrConnection> _conns; // 管理所有Connection连接
uint64_t conn_id = 0;
LoopThreadPool *loop_pool;

void OnConnected(const PtrConnection &conn)
{
    DBG_LOG("NEW ACCEPT:%p", conn.get());
}

void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    // 这里的buf就是Connection连接的输入缓冲区
    buf->MoveReadOffset(buf->ReadAbleSize()); // 模拟一下，已经处理了读到的数据
    const char *data = "hello world";
    conn->Send(data, strlen(data));
}

void OnClosed(const PtrConnection &conn)
{
    _conns.erase(conn->Id());
}

void NewConnection(int newfd)
{
    conn_id++; // 连接的ID
    PtrConnection conn(new Connection(loop_pool->NextLoop(), conn_id, newfd));
    /*我们设置的这三个回调，其实更多的是对缓冲区进行操作*/
    conn->SetConnectedCalllback(std::bind(OnConnected, std::placeholders::_1));
    conn->SetMessageCalllback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSrvClosedCalllback(std::bind(OnClosed, std::placeholders::_1));

    /*必须先添加定时销毁任务，然后启动读监控,应为启动了读监控可能立即就有事件触发，这时会触发任意事件刷新定时任务，但是我们还有没添加定时任务，会出错*/
    conn->EnableInactiveRelease(10); // 添加定时销毁任务
    conn->Established();             // 启动初始化

    _conns.insert(std::make_pair(conn_id, conn)); // 将当前connection插入到_conns中
    DBG_LOG("NEW______________________");
}

int main()
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->CreatAndStart();

    Acceptor acceptor(&base_loop, 8888);
    acceptor.SetAcceptCallBack(std::bind(NewConnection, std::placeholders::_1));
    acceptor.Listen();

    base_loop.Start();
    return 0;
}